package qjs.com.vn.action;

import java.util.ArrayList;
import java.util.List;

/*import org.apache.struts2.ServletActionContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
*/
import qjs.com.vn.model.User;
import qjs.com.vn.service.UserService;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

@SuppressWarnings("serial")
public class LoginAction extends ActionSupport implements ModelDriven<Object> {
//public class LoginAction extends ActionSupport  {
	User user = new User();
	UserService userService; 
	
	@Override
	public Object getModel() {
		clearActionErrors();
		return user;
	}
	
	public String execute() throws Exception {
		return "input";
	}
	
	//public void validate() {
	public String checkLogin() throws Exception {
		List<User> listUser = new ArrayList<User>();
		Boolean rs = false;
		String un = "";
		String pw = "";
		
		if (null != userService) {
			listUser = userService.listUser();
		}	
		
		if (null != user ) {
			un = user.getUsername().toString();
			pw = user.getPassword().toString();	
		}		
		
		if (null != listUser) {
			for (User i : listUser) {
				if(un.equals(i.getUsername().toString()) && pw.equals(i.getPassword().toString()) ) {
					rs = true;
					//update back to User model
					userModelUpdateBack(i);
					//exit out loop
					break;
				}
			}
		}
		
		if (rs == true)	{			
			//check value "Save login" function
			userService.updateUser(user.isInuse(), user);
			
		    return "success";
		}
		else {			
			if (null != un || null != pw) {
				addActionError(getText("login.message.error"));	
			}			
			return "input";
		}		
	}
	
	public String userLogout() throws Exception {
		return "success";
		//return "error";
	}
	
	public String menuBaobi() throws Exception {
		return "success";
	}
	
	public String menuNguyenlieu() throws Exception {
		return "success";
	}
	
	public String menuBbThanhpham() throws Exception {
		return "success";
	}
	
	public String menuSanpham() throws Exception {
		return "success";
	}
	
	public String menuQuantri() throws Exception {
		return "success";
	}
	
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	public void userModelUpdateBack(User i) throws Exception{
		if (null != i.getCallname()) {
			user.setCallname(i.getCallname());
		}
		if (null != i.getRolecode()) {
			user.setRolecode(i.getRolecode());
		}
		if (null != i.getRolename()) {
			user.setRolename(i.getRolename());
		}
		if (null != i.getDescription()) {
			user.setDescription(i.getDescription());
		}
	}
	
}
